﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MessageSystem.Default.infrastructure
{
    class memory
    {
        public virtual void create()
        {
            strategy_ = new strategy(options.max_msg_cache_size, options.max_block_cache_size, options.max_message_size);
            block_pool = new list_block();
            block_pool.clear();
            msg_pool = new list_msg();
            msg_pool.clear();            
        }

        public block alloc_block()
        {
            block ret = null;
            ret = block_pool.get();
            if (null == ret)
                ret = strategy_.alloc_block();
            ret.next = null;
            ret.refcount = 1;

            return ret;
        }

        public void free_block(block ptr_block)
        {
            if (null != ptr_block && ptr_block.release())
            {
                if (strategy_.free_block(ptr_block))
                {
                    block_pool.add_head(ptr_block);
                }
            }
        }

        public msg alloc_msg()
        {
            msg ret = null;
            ret = msg_pool.get();
            if (null == ret)
                ret = strategy_.alloc_msg();

            ret.next = null;
            ret.readpos = 0;
            ret.writepos = 0;
            ret.data = null;
            ret.totalsize = 0;

            return ret;
        }

        public void free_msg(msg ptr_msg)
        {
            if (null == ptr_msg)
                return;

            if (null != ptr_msg.data)
                free_block(ptr_msg.data);
            ptr_msg.data = null;

            if (strategy_.free_msg(ptr_msg))
                msg_pool.add_head(ptr_msg);
        }

        private strategy strategy_;
        private list_block block_pool;
        private list_msg msg_pool;
    }
}
